<template>
    <div class="dv-wrapper" :id="data.id" :style="wrapperStyle"></div>
</template>

<script>
    import {computed, nextTick, ref, toRefs, watch} from 'vue'
    import {ApiType} from '@/config/data-source'
    import {isEmpty, throwError, toJson} from '@/utils/util'
    import {getModelDataById} from '@/api/screen/index'
    import {useStore} from 'vuex'
    import {PivotSheet} from '@antv/s2';

    export default {
        name: 'VPivotTable',
        props: {
            data: {
                type: Object,
                required: true,
            },
        },
        setup(props) {
            let s2
            const {apiData} = toRefs(props.data)
            const dvData = ref({})
            const tableRef = ref(null)

            // config 配置项
            const config = computed(() => props.data.config)
            // attr 属性
            const attr = computed(() => {
                return props.data.attr
            })
            // 容器style
            const wrapperStyle = computed(() => {
                return `width: ${attr.value.w}px, height: ${attr.value.h}px`
            })
            function getTableData() {
                // 静态数据，直接返回header和data
                if (apiData.value.type === ApiType.static) {
                    return {
                        header: dvData.value.header ?? [],
                        data: dvData.value.data ?? [],
                    }
                } else {
                    const {config: apiCfg} = apiData.value
                    // 动态组装header
                    const firstX = apiCfg.x.map(i => i.title).join('-')
                    const otherX = apiCfg.y.map(i => i.title)
                    // 动态组装表格数据
                    const rows = []
                    if (dvData.value.list) {
                        dvData.value.list.forEach(item => {
                            let rowss = []
                            Object.keys(item).forEach(function (key) {
                                rowss.push(item[key]);
                            });
                            rows.push(rowss)
                        })
                    }
                    console.log(rows)
                    return {
                        header: [firstX, ...otherX],
                        data: rows,
                    }
                }
            }

            const options = computed(() => {
                const cfg = config.value
                // 根据是否显示行号，拼接宽度及对齐方式
                const columnWidth = cfg.index ? [cfg.indexWidth, ...cfg.columnWidth] : [...cfg.columnWidth]
                const align = cfg.index ? [cfg.indexAlign, ...cfg.align] : [...cfg.align]
                return {
                    ...getTableData(),
                    rowNum: cfg.rowNum,
                    headerBGC: cfg.headerBGC,
                    oddRowBGC: cfg.oddRowBGC,
                    evenRowBGC: cfg.evenRowBGC,
                    waitTime: cfg.waitTime,
                    headerHeight: cfg.headerHeight,
                    indexHeader: cfg.indexHeader,
                    carousel: cfg.carousel,
                    hoverPause: cfg.hoverPause,
                    index: cfg.index,
                    columnWidth,
                    align,
                }
            })

            const $store = useStore()
            // 设置dvData，读取数据并塞入存储数据
            const setDvData = async (filters = []) => {
                const {type, config: apiCfg} = apiData.value
                $store.commit('schema/setLoading', true)
                try {
                    // 获取源数据
                    if (type === ApiType.static) {
                        dvData.value = toJson(apiCfg.data, {})
                        const s2options = {
                            width: attr.value.w,
                            height: attr.value.h
                        }
                        const container = document.getElementById(props.data.id);
                        s2 = new PivotSheet(container, dvData.value, s2options)
                        s2.render()
                    } else {
                        const {modelId, x, y} = apiCfg
                        const cfgFilters = apiCfg.filters || []
                        if (!isEmpty(modelId) && !isEmpty(y)) {
                            dvData.value = await getModelDataById({
                                modelId,
                                x,
                                y,
                                filters: [...cfgFilters, ...filters],
                            })
                            getTableData()
                        }
                    }
                } catch (e) {
                    throwError('scroll-table/setDvData', e)
                }
                // setTimeout(() => {
                $store.commit('schema/setLoading', false)
                // }, 800)
            }

            watch(
                [
                    () => apiData.value.type,
                    () => apiData.value.config.data,
                    () => apiData.value.config.x,
                    () => apiData.value.config.y,
                ],
                async () => {
                    nextTick(() => {
                        setDvData()
                    })
                },
                {deep: true, immediate: true},
            )
            watch(
                [
                    () => dvData.value,
                    () => config.value,
                ],
                () => {
                    nextTick(() => {
                        tableRef.value
                    })
                },
                {deep: true, immediate: true},
            )
            return {
                tableRef,
                attr,
                config,
                wrapperStyle,
                options,
            }
        },
    }
</script>
